
let express = require('express');
let router = express.Router();
let adminDao = require('../../model/backend/admin')
let SMSClient = require('@alicloud/sms-sdk');
let accessKeyId = 'LTAIBJlRUGI3tCsV';
let secretAccessKey = 'GOmWRR8LIBfITsGPR6IYkvBql8GLvz';

//短信验证码发送api
router.post('/send',async function (req,res) {
  let  phone = req.body.phone;  
  let testRule =/^[1][3,4,5,7,8][0-9]{9}$/;
  if (!phone) {
      return await res.json({
          status: 203,
          msg: "请输入手机号"
      })
  }
  //验证手机号格式
  if(!testRule.test(phone)){
      return await res.json({status:203,msg:'手机号格式错误，请重新输入'})
  }
  let  getSendCodeNum   = await adminDao.getSendCodeNum(phone);
  if(getSendCodeNum.length>15){
    return await res.json({status:203,msg:"您的手机号发送验证码已超过次数，请24小时后再进行操作！"})  
  }
  //生成6位随机验证码
  let code = "";
  for (var i = 0; i < 6; i++) {
      code += Math.floor(Math.random() * 10);
  }
  let smsClient = new SMSClient({
      accessKeyId,
      secretAccessKey
  });
  await adminDao.setCode(phone, code);
  await smsClient.sendSMS({
      PhoneNumbers: phone,
      SignName: '礼意',
      TemplateCode: 'SMS_135585112',
      TemplateParam: `{"code":${code}}`
  }).then(function (result) {
      let {
          Code
      } = result
      if (Code === 'OK') {
          res.json({
              status: 200,
              msg: 'success'
          })
      }
  }, function (err) {
      res.json({
          status: 500,
          msg: '验证码发送失败，请重新获取！'
      })
  })
})




module.exports=router;